package com.py.payment.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.py.payment.dto.ret.IngredientRecordDto;
import com.py.payment.dto.ret.InvestmentRetDto;
import com.py.payment.entity.*;
import com.py.payment.running.TimeRun;
import com.py.payment.service.*;
import com.py.payment.tools.ToolsUtils;
import com.py.payment.tools.date.DateUtils;
import com.py.payment.tools.response.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/index")
@CrossOrigin(origins = "*")
public class indexController {

    @Autowired
    private PyInvestmentService investmentService;

    @Autowired
    private PySystemConfigService systemConfigService;

    @Autowired
    private PyIngredientsService ingredientsService;

    @Autowired
    private PyPayRecordsService payRecordsService;

    @Autowired
    private PyInfoTypeService infoTypeService;

    @Autowired
    private PySiteNumericService siteNumericService;

    @Autowired
    private PyIngredientsRecordService ingredientsRecordService;

    @Autowired
    private TimeRun timeRun;

    @PostMapping(name = "获取资金到账情况",path = "/getInvestment")
    public ResponseData getInvestment(){
        List<InvestmentRetDto> investmentRetDtoList = this.investmentService.getInvestment();
        return ResponseData.success(investmentRetDtoList);
    }

    @PostMapping(name = "获取付款情况",path = "/getSystemConfig")
    public ResponseData getSystemConfig(){
        QueryWrapper<PySystemConfig> systemConfigQueryWrapper = new QueryWrapper<>();
        systemConfigQueryWrapper.orderByDesc("id");
        systemConfigQueryWrapper.last("limit 1");
        PySystemConfig systemConfig = this.systemConfigService.getOne(systemConfigQueryWrapper);
        return ResponseData.success(systemConfig);
    }

    @PostMapping(name = "获取站点原材料信息",path = "/getIngredientRecordList")
    public ResponseData getIngredientRecordList(@RequestBody PyIngredientsRecord ingredientsRecord){
        List<PyIngredients> ingredientsList = this.ingredientsService.list();
        List<String> xData = ingredientsList.stream().map(PyIngredients::getTitle).toList();
        List<String> predefinedNumberList = new ArrayList<>();
        List<String> numericValueList = new ArrayList<>();
        String newDateStr = DateUtils.dateToDateStr(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        for (PyIngredients item : ingredientsList) {
            QueryWrapper<PySiteNumeric> siteNumericQueryWrapper = new QueryWrapper<>();
            siteNumericQueryWrapper.eq("site_id", ingredientsRecord.getSiteId());
            siteNumericQueryWrapper.eq("ingredient_id", item.getId());
            siteNumericQueryWrapper.orderByDesc("id");
            siteNumericQueryWrapper.last("limit 1");
//            PySiteNumeric siteNumeric = this.siteNumericService.getOne(siteNumericQueryWrapper);
            QueryWrapper<PyIngredientsRecord> qw = new QueryWrapper<>();
            qw.eq("site_id",ingredientsRecord.getSiteId());
            qw.eq("investment_id",item.getId());
            qw.orderByDesc("create_time");
            qw.last("limit 1");
            PyIngredientsRecord record = this.ingredientsRecordService.getOne(qw);
            String predefinedNumber = "0";
            String numericValue = "0";
            if(ToolsUtils.isNotEmpty(record)){
                newDateStr = DateUtils.dateToDateStr(record.getCreateTime(),DateUtils.YYYY_MM_DD_HH_MM_SS);
                if(ToolsUtils.isNotEmpty(record.getPredefinedNumber())){
                    predefinedNumber = record.getPredefinedNumber();
                    predefinedNumberList.add(predefinedNumber);
                }
                if(ToolsUtils.isNotEmpty(record.getNumericValue())){
                    numericValue = record.getNumericValue();
                    numericValueList.add(numericValue);
                }
            }
        }
        IngredientRecordDto ingredientRecordDto = new IngredientRecordDto();
        ingredientRecordDto.setNewDate(newDateStr);
        ingredientRecordDto.setXData(xData);
        ingredientRecordDto.setPredefinedNumberList(predefinedNumberList);
        ingredientRecordDto.setNumericValueList(numericValueList);
        return ResponseData.success(ingredientRecordDto);
    }

    @PostMapping(name = "支付台账首页-上方信息",path = "/getPayMantTopInfo")
    public ResponseData getPayMantTopInfo(){
        String deadline = DateUtils.dateToDateStr(new Date(), "yyyy-MM");
        QueryWrapper<PyPayRecords> payRecordsQueryWrapper = new QueryWrapper<>();
        payRecordsQueryWrapper.select("IFNULL(sum(accounts_payable),0) accountsPayable,IFNULL(sum(net_payment),0) netPayment");
        PyPayRecords records = this.payRecordsService.getOne(payRecordsQueryWrapper);

        BigDecimal accountsPayable = new BigDecimal(records.getAccountsPayable());
        BigDecimal netPayment = new BigDecimal(records.getNetPayment());
        BigDecimal deduction = accountsPayable.subtract(netPayment);

        JSONObject json = new JSONObject();
        json.put("deadline",deadline);
        json.put("accountsPayable",accountsPayable.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        json.put("netPayment",netPayment.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        json.put("deduction",deduction.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        return ResponseData.success(json);
    }

    @PostMapping(name = "支付台账首页-下方信息",path = "/getPayMantBelowInfo")
    public ResponseData getPayMantBelowInfo(){
        QueryWrapper<PyInfoType> infoTypeQueryWrapper = new QueryWrapper<>();
        infoTypeQueryWrapper.eq("status",1);
        List<PyInfoType> infoTypeList = this.infoTypeService.list(infoTypeQueryWrapper);

        List<PyPayRecords> payRecordsList = new ArrayList<>();
        infoTypeList.forEach(item->{
            QueryWrapper<PyPayRecords> payRecordsQueryWrapper = new QueryWrapper<>();
            payRecordsQueryWrapper.select("IFNULL(sum(net_payment),0) netPayment,type");
            payRecordsQueryWrapper.eq("type",item.getId());
            PyPayRecords records = this.payRecordsService.getOne(payRecordsQueryWrapper);
            BigDecimal netPayment = new BigDecimal(records.getNetPayment()).setScale(2, BigDecimal.ROUND_HALF_UP);
            records.setNetPayment(netPayment.toPlainString());
            payRecordsList.add(records);
        });
        return ResponseData.success(payRecordsList);
    }

    @PostMapping(name = "生成随机正负数",path = "/generateNumeric")
    public ResponseData generateNumeric(@RequestBody PyIngredientsRecord ingredientsRecord){
        return ResponseData.success(this.timeRun.generateNumeric(ingredientsRecord.getPredefinedNumber()));
    }
}
